package com.helios.core.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.helios.core.bean.Config;
import com.helios.core.mapper.ConfigMapper;
import com.helios.core.util.RedisUtil;

/**
 * 配置信息数据服务.
 * 
 * @author liyu
 */
@Service
public class ConfigService extends ServiceAdapter<Config> {

    @Autowired
    private ConfigMapper configMapper;
    
    @Value("#{configProperties.bean_config_time}")
    private int cacheTime;

    @Override
    public String getDispInfo() {
        return "配置信息";
    }

    @Override
    public String getCacheKey(Object args) {
        if(args instanceof Config) {
            return "CONFIG_" + ((Config) args).getId();
        } else {
            return "CONFIG_" + args.toString();
        }
    }

    @Override
    public int getCacheTime() {
        return cacheTime;
    }
    
    public List<Config> gets() {
        return configMapper.gets();
    }
    
    public Map<String, Config> getAsMap() {
        Map<String, Config> configMap = RedisUtil.getMap("CONFIG_MAP");
        if(configMap == null) {
            final Map<String, Config> temp = new HashMap<>();
            gets().forEach((config) -> {
                temp.put(config.getKey(), config);
            });
            configMap = temp;
            RedisUtil.putMap("CONFIG_MAP", configMap, getCacheTime());
        }
        return configMap;
    }
    
    public String get(String key) {
    	return getAsMap().get(key).getValue();
    }
}
